package android.twitter.clientroid;

import java.util.ArrayList;

import org.json.JSONObject;

import twitter4j.Twitter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SearchActivity extends Activity
{
	private EditText tvSearch;
	private Button submitSearch;
	SharedPreferences settings;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchpage);
        
        tvSearch = (EditText) this.findViewById(R.id.tb_search);
        
        submitSearch = (Button) this.findViewById(R.id.btn_search);
        submitSearch.setOnClickListener(
    		new View.OnClickListener()
    		{
    			@Override
    			public void onClick(View v)
    			{
    				String word = tvSearch.getText().toString();
    				if(word.length() == 0)
    				{
    					Toast.makeText(SearchActivity.this, "please write a word", Toast.LENGTH_LONG).show();
    					return;
    				}
    				
					SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
					String accessTokenToken = settings.getString("accessTokenToken", null);
					String accessTokenSecret = settings.getString("accessTokenSecret", null);
					if(accessTokenToken == null || accessTokenSecret == null)
					{
						//access token is null
						Toast.makeText(SearchActivity.this, "please relogin", Toast.LENGTH_LONG).show();
						Intent loginIntent = new Intent(SearchActivity.this, LoginActivity.class);
						startActivity(loginIntent);
					}
					else
					{
						//access token exists
						Toast.makeText(SearchActivity.this, "searching ...", Toast.LENGTH_LONG).show();
						Twitter preAuthorizedTwitter = ((TwitterApplication)getApplication()).getTwitter();
						ArrayList<JSONObject> jobs = TweetReader.retrieveSpecificTweets(preAuthorizedTwitter, word);
						if (jobs.size() > 0)
						{
							Globals.tweets = jobs;
							Intent listIntent = new Intent(SearchActivity.this, SearchResultsActivity.class);
							startActivity(listIntent);
						}
						
						else
						{
							Toast.makeText(SearchActivity.this, "Nothing found !", Toast.LENGTH_LONG).show();
						}
					}
    			}
    	});
        
    }
    
}